package com.lw.service.impl;

import com.lw.common.utils.StrUtils;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.lw.entity.TbUserRole;
import com.lw.mapper.TbUserRoleMapper;
import com.lw.service.TbUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.lw.entity.table.TbRoleTableDef.TB_ROLE;
import static com.lw.entity.table.TbUserRoleTableDef.TB_USER_ROLE;

/**
 * 用户和角色关联表 服务层实现。
 *
 * @author lw
 * @since 2025年05月16日 00:25:08
 */
@Service
public class TbUserRoleServiceImpl extends ServiceImpl<TbUserRoleMapper, TbUserRole> implements TbUserRoleService {

    @Resource
    private TbUserRoleMapper tbUserRoleMapper;


    @Override
    public Set<Long> getRoleListByUserId(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(TB_USER_ROLE.USER_ID.getName(), userId);
        List<TbUserRole> tbUserRoles = tbUserRoleMapper.selectListByQuery(queryWrapper);
        return tbUserRoles.stream().map(TbUserRole::getRoleId).collect(Collectors.toSet());
    }

    @Override
    public List<Long> getUserListByRole(List<String> roleList, String rootRoleName) {
        if (roleList.isEmpty()) {
            return null;
        }
        QueryChain<TbUserRole> queryWrapper = queryChain().select(TB_USER_ROLE.USER_ID).from(TB_USER_ROLE)
                .leftJoin(TB_ROLE).on(TB_USER_ROLE.ROLE_ID.eq(TB_ROLE.ID))
                .where(TB_USER_ROLE.ROLE_ID.in(roleList));
        if (StrUtils.hasLength(rootRoleName)) {
            queryWrapper.and(TB_ROLE.CODE.eq(rootRoleName));
        }
        return queryWrapper.listAs(Long.class);
    }

    @Override
    public List<TbUserRole> getUserListByRoleId(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(TB_USER_ROLE.USER_ID.getName(), id);
        return list(queryWrapper);
    }

    @Override
    public boolean deleteUserRoleByUserId(Long id) {
        QueryWrapper queryWrapper = QueryWrapper.create().eq(TB_USER_ROLE.USER_ID.getName(), id);
        return remove(queryWrapper);
    }

}
